package com.elite.groovy.callback

import com.alibaba.nls.client.AccessToken
import com.elite.groovy.kh.KHDBConfig
import com.elite.groovy.kh.KHUtil
import com.elite.groovy.util.EliteBean
import com.elite.groovy.util.IpAddressUtil
import com.elite.groovy.util.Util
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.text.SimpleDateFormat

/**
 * @projectName: Groovy*
 * @package: com.elite.groovy.callback*
 * @className: apiAPIDemo
 * @description: 标准接口测试Demo。
 * @author: Tao
 * @date: 2024-05-19 15:00
 * @version: 1.0
 */
public class apiAPIUploadBase64 implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiAPIUploadBase64.class);

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");


    String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        long startTime = System.currentTimeMillis();
        JSONObject outData = JSONObject.fromObject("{\"code\":1,\"message\":\"操作成功\"}");

        // 调用IP过滤
        if (KHDBConfig.getParam(eliteBean, "#APIIP") == "1" && !KHUtil.getRemoteHost(request)) {
            outData.put("code", -1);
            outData.put("message", "API被非法IP调用-Request Not Allow!" + IpAddressUtil.getIpAddress(request));
            log.warn(outData);
            return outData;
        }

        String getMethod = request.getMethod();
        log.debug("HTTP请求调用类型 getMethod:" + getMethod);
        if (getMethod != "POST" && getMethod != "GET") {
            outData.put("code", -1);
            outData.put("message", "HTTP请求调用类型错误，接口调用失败：" + getMethod);
            log.error(outData);
            return outData;
        }

        // 获取所有Header
        Map<String, String> mapHeader = new HashMap<String, String>();
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            log.debug("Call Header-" + key + ":" + value);

            mapHeader.put(key, value);
        }

        // 获取所有参数名
        Map<String, String> mapParam = new HashMap<String, String>();
        Enumeration ep = request.getParameterNames();
        while (ep.hasMoreElements()) {
            String key = (String) ep.nextElement();
            String value = request.getParameter(key);
            log.debug("Call Parameter-" + key + ":" + value);
            mapParam.put(key, value);

        }

        // 获取数据源List<Map<String, Object>>
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        // 获取调用数据
        String Syncpram = "";
        if (getMethod.equals("GET")) {
            Syncpram = request.getQueryString();
            log.info("接收调用GET参数信息：" + Syncpram);
        } else if (getMethod.equals("POST")) {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                Syncpram += line;
            }
            log.info("接收调用POST报文信息：" + System.getProperty("line.separator") + Syncpram);
        }

        try {
            // 解析请求报文
            String mime = mapParam.get("mime");
            String upfile_b64 = mapParam.get("upfile_b64")

            String file_Src = KHDBConfig.getParamConfig(eliteBean, "SYS_TempFilesPath") + "/Upload_Files/" + sdf.format(new Date());
            if (mime.equals("audio/pcm")) {
                file_Src = file_Src + ".pcm";
                boolean res_Code = base64ToFile(file_Src, upfile_b64);

                outData.put("data", "https://ccctest.davco.cn/ngs/fs/get?file=" + file_Src.replace("/nas/davco_cc/ngs", ""));
            } else if (mime.equals("audio/mp3")) {
                file_Src = file_Src + ".mp3";
                boolean res_Code = base64ToFile(file_Src, upfile_b64);

                outData.put("data", getAudioText("https://ccctest.davco.cn/ngs/fs/get?file=" + file_Src.replace("/nas/davco_cc/ngs", "")));
            } else {
                outData.put("code", -1);
                outData.put("message", "暂不支持的上传文件类型，文件类型mime：" + mime);
            }

        } catch (Exception e) {
            outData.put("code", -1);
            outData.put("message", "HTTP请求调用错误，接口处理异常：" + e.getMessage());
            log.error(outData, e);

        }
        return outData;
    }

    public static boolean base64ToFile(String src, String base64String) {
        boolean res_Code = true;
        try {
            byte[] decodedBytes = Base64.getDecoder().decode(base64String);

            FileOutputStream outputStream = new FileOutputStream(src);
            outputStream.write(decodedBytes);
            outputStream.close();

            log.debug("音频文件已成功生成！");
        } catch (IOException e) {
            res_Code = false;
            e.printStackTrace();
        }
        return res_Code;
    }

    public static String getAudioText(String audio_address) {

        String res_Text = "";
        String accessKeyId = "LTAI5tKC9nScDe6B77ocmqqN";
        String accessKeySecret = "JJDA4twalK7zviUlvzA5UxEzsSm8Ef";
        System.out.println("accessKeyId=" + accessKeyId + "; accessKeySecret=" + accessKeySecret);
        AccessToken accessToken = new AccessToken(accessKeyId, accessKeySecret);
        try {
            accessToken.apply();
            log.debug("Token: " + accessToken.getToken() + ", expire time: " + accessToken.getExpireTime());

            String call_URL = "https://nls-gateway-cn-shanghai.aliyuncs.com/stream/v1/FlashRecognizer?appkey=CnVAsCQQaPZkUv60&token=" + accessToken.getToken() + "&format=mp3&sample_rate=16000&audio_address=" + audio_address;
            log.debug("请求URL：" + call_URL);

            // 处理头文件
            Map<String, String> headerMap = new HashMap<String, String>();
            headerMap.put("Content-type", "application/text");

            String postResult = Util.doHttpPostUseHead(call_URL, "", "UTF-8", 120000, 0, headerMap);
            log.debug("返回请求体：" + postResult);

            JSONObject res_Body = JSONObject.fromObject(postResult);

            String status = KHUtil.GetSFJV(res_Body, "status");
            String message = KHUtil.GetSFJV(res_Body, "message");
            if (status.equals("20000000")) {
                JSONArray sentences = res_Body.getJSONObject("flash_result").getJSONArray("sentences");
                for (int i = 0; i < sentences.size(); i++) {
                    res_Text = res_Text + sentences.getJSONObject(0).getString("text");
                }
            } else {
                res_Text = "获取音频文本数据错误:" + message;
            }

        } catch (Exception e) {
            res_Text = "获取音频文本数据异常:" + e.getMessage();
            log.error(res_Text, e);
        }

        return res_Text;
    }
}